#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@file uart_driver.py
@brief UART串口驱动层
@details 提供独立的UART串口通信接口，专门用于日志监控
@author Motor Controller Team
@date 2024
"""

import logging
import time
import serial
from typing import Optional, List
from core.logging_config import get_logger

logger = get_logger(__name__)


class UARTDriver:
    """
    @brief UART串口驱动类
    @details 负责与开发板的UART串口通信，专门用于日志监控
    """
    
    def __init__(self, port: str, baudrate: int = 115200, 
                 timeout: float = 1.0, bytesize: int = 8, 
                 parity: str = 'N', stopbits: int = 1):
        """
        @brief 初始化UART驱动
        @param port 串口端口
        @param baudrate 波特率
        @param timeout 超时时间
        @param bytesize 数据位
        @param parity 校验位
        @param stopbits 停止位
        """
        self.port = port
        self.baudrate = baudrate
        self.timeout = timeout
        self.bytesize = bytesize
        self.parity = parity
        self.stopbits = stopbits
        
        self.serial_conn: Optional[serial.Serial] = None
        self.connected = False
        
        logger.info(f"UART驱动初始化 - 端口: {port}, 波特率: {baudrate}")
    
    def connect(self) -> bool:
        """
        @brief 连接UART串口
        @return 连接是否成功
        """
        try:
            if self.connected:
                logger.warning("UART串口已连接")
                return True
            
            # 创建串口连接
            self.serial_conn = serial.Serial(
                port=self.port,
                baudrate=self.baudrate,
                bytesize=self.bytesize,
                parity=self.parity,
                stopbits=self.stopbits,
                timeout=self.timeout
            )
            
            # 等待连接稳定
            time.sleep(0.5)
            
            if self.serial_conn.is_open:
                self.connected = True
                logger.info(f"UART连接成功 - 端口: {self.port}")
                return True
            else:
                logger.error(f"UART连接失败 - 端口: {self.port}")
                return False
                
        except Exception as e:
            logger.error(f"UART连接异常 - 端口: {self.port}, 错误: {e}")
            self.connected = False
            return False
    
    def disconnect(self) -> bool:
        """
        @brief 断开UART串口连接
        @return 断开是否成功
        """
        try:
            if self.serial_conn and self.serial_conn.is_open:
                self.serial_conn.close()
                logger.info(f"UART连接已断开 - 端口: {self.port}")
            
            self.connected = False
            self.serial_conn = None
            return True
            
        except Exception as e:
            logger.error(f"UART断开连接异常: {e}")
            return False
    
    def is_connected(self) -> bool:
        """
        @brief 检查UART连接状态
        @return 是否已连接
        """
        return self.connected and self.serial_conn and self.serial_conn.is_open
    
    def send_command(self, command: str) -> str:
        """
        @brief 发送UART命令
        @param command 要发送的命令
        @return 发送结果
        """
        try:
            if not self.is_connected():
                return "错误: UART串口未连接"
            
            # 发送命令
            command_bytes = command.encode('utf-8')
            self.serial_conn.write(command_bytes)
            
            # 等待响应
            time.sleep(0.1)
            
            # 读取响应
            try:
                if self.serial_conn.in_waiting > 0:
                    response = self.serial_conn.read(self.serial_conn.in_waiting)
                    if response:
                        return response.decode('utf-8', errors='ignore')
            except Exception as read_error:
                logger.warning(f"读取响应时出错: {read_error}")
            
            return "无响应"
                
        except Exception as e:
            logger.error(f"发送UART命令异常: {e}")
            return f"错误: {e}"
    
    def receive_data(self) -> str:
        """
        @brief 接收UART数据
        @return 接收到的数据
        """
        try:
            if not self.is_connected():
                return "错误: UART串口未连接"
            
            # 检查是否有数据可读
            if self.serial_conn.in_waiting > 0:
                data = self.serial_conn.read(self.serial_conn.in_waiting)
                if data:
                    # 解码数据并清理
                    decoded_data = data.decode('utf-8', errors='ignore').strip()
                    if decoded_data:
                        return decoded_data
            else:
                # 尝试读取少量数据
                try:
                    data = self.serial_conn.read(1)  # 读取1个字节
                    if data:
                        # 继续读取更多数据
                        time.sleep(0.01)  # 短暂等待
                        if self.serial_conn.in_waiting > 0:
                            more_data = self.serial_conn.read(self.serial_conn.in_waiting)
                            data += more_data
                        
                        # 解码数据
                        decoded_data = data.decode('utf-8', errors='ignore').strip()
                        if decoded_data:
                            return decoded_data
                except:
                    pass
                    
            return ""
                
        except Exception as e:
            logger.error(f"接收UART数据异常: {e}")
            return f"错误: {e}"
    
    def get_port_info(self) -> dict:
        """
        @brief 获取串口信息
        @return 串口信息字典
        """
        return {
            "port": self.port,
            "baudrate": self.baudrate,
            "timeout": self.timeout,
            "bytesize": self.bytesize,
            "parity": self.parity,
            "stopbits": self.stopbits,
            "connected": self.connected
        }
